/* $RCSFile: SilverModule.ascx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/PageModules/SilverModule/SilverModule.ascx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:22  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:59  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:26  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.Core;
using AddonNice.UI;
using AddonNice.UI.WebControls;
using AddonNice.UI.DataTypes;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Diagnostics;
using AddonNice.CRMWrapper;

using Telerik.Web.UI;

using Trace2    = System.Diagnostics.Trace;

namespace AddonNice.PageModules.SilverModule
{
 	#region Local TraceSwitch 
	public class SilverTrace : ADNTraceSwitch
	{
		static public ADNTraceSwitch	Sw	            =	new ADNTraceSwitch("SilverTrace","Special Trace Switch for SilverModule");
	}
	#endregion Local TraceSwitch 

    /// <summary>
    /// Initializer class for SilverModule 
    /// </summary>
    public class SilverModuleSI : PortalCRMModuleControlSI
    {
        public SilverModuleSI(ModuleSettingsDictionary bSettings,ISettingsOwner pm) : base()
        {
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModuleSI Ctor BEG.",ModuleTraceSwitch.Sw.Info);
            InitSettings(bSettings,pm);
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModuleSI Ctor END.",ModuleTraceSwitch.Sw.Info);
        }
 
        public override void InitSettings(ModuleSettingsDictionary bSettings,ISettingsOwner pm)
        {             
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModuleSI InitSettings BEG.",ModuleTraceSwitch.Sw.Info);
            
            base.InitSettings(bSettings,pm);

            string extgrp                       =   pm.ExtendedResourcesGroup;

			SettingItemSpecial url              =   new SettingItemSpecial("SILVER_SRC",new UploadedFileDataType2(UploadFileType.SilverLight));
			//url.Required                        =   true;
            url.ExtendedGroupName               =   extgrp;
			url.Order                           =   20;
			//url.Value                           =   portalSettings.DefaultSilverlightVirtualPath;
            url.EnglishName                     =   "Source";
            url.Description                     =   "Source";
			bSettings.AddSetting(url);

			SettingItemSpecial width            =   new SettingItemSpecial("SILVER_WIDTH",new UnitDataType());
			//width.Required                      =   true;
			width.ExtendedGroupName             =   extgrp;
			width.Order                         =   25; 
			width.Value                         =   "100%";
            width.EnglishName                   =   "Width";
            width.Description                   =   "Width";
			bSettings.AddSetting(width);

			SettingItemSpecial height           =   new SettingItemSpecial("SILVER_HEIGHT",new UnitDataType());
			//height.Required                     =   true;
			height.ExtendedGroupName            =   extgrp;
			height.Order                        =   30;
			height.Value                        =   "100%";
            height.EnglishName                  =   "Height";
            height.Description                  =   "Height";
            bSettings.AddSetting(height);

			SettingItemSpecial backColor        =   new SettingItemSpecial("SILVER_BACKCOLOR",new ColorDataType("White"));
			//backColor.Required                =   true;
			backColor.ExtendedGroupName         =   extgrp;
			backColor.Order                     =   40;
            backColor.EnglishName               =   "Background Color";
            backColor.Description               =   "Background Color";
            bSettings.AddSetting(backColor);

            SettingItemSpecial htmlAccess       =   new SettingItemSpecial("SILVER_ENABLEHTMLACCESS",new BooleanDataType());
			htmlAccess.ExtendedGroupName        =   extgrp;
			htmlAccess.Order                    =   50;
			htmlAccess.Value                    =   StStr.strTrue;
            htmlAccess.EnglishName              =   "Enable html Access";
            htmlAccess.Description              =   "Enable page html Access from silverlight module";
            bSettings.AddSetting(htmlAccess);

            SettingItemSpecial initParam        =   new SettingItemSpecial("SILVER_INITPARAMS",new StringDataType());
			initParam.ExtendedGroupName         =   extgrp;
			initParam.Order                     =   60;
            initParam.EnglishName               =   "Silverlight init parameters";
            initParam.Description               =   "Comma separated list of paremeter=value to transmit to Silverlight module";
            bSettings.AddSetting(initParam);

            WSListDataType defAcc               =   new WSListDataType(CrmStr.systemuser,"name", "ID");
            SettingItemSpecial ModuleOwner      =   new SettingItemSpecial("SILVER_OWNER",defAcc);
            ADNDynSystemUser wsys               =   null;
            if (!string.IsNullOrEmpty(Config.CRMDefaultAccount))
            {
                string domainName               =   string.Format("{0}\\{1}",Config.CRMDefaultAccountDomain,Config.CRMDefaultAccount);
                wsys                            =   Wrapper.Util.FindSystemUserByDomainName(domainName);
            }
            else 
            {
                wsys                            =   DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),Wrapper.adminUserId);
            }
            if (wsys != null)
            {       
                ModuleOwner.Value               =   wsys.systemuserid.ToString();
                defAcc.DisplayTextValue         =   wsys.fullname;
            }
            ModuleOwner.EnglishName             =   "Owner";
            ModuleOwner.Order                   =   70;
            ModuleOwner.ExtendedGroupName       =   extgrp;
            ModuleOwner.Description             =   " Choose the owner for leads created with this module";
            ModuleOwner.SettingItemsEvent       +=  new SettingItemsEventHandler(ModuleOwner_SettingItemsEvent);
            bSettings.AddSetting(ModuleOwner);
            
            SettingItemSpecial UseRedirect      =   new SettingItemSpecial("SILVER_USEPAGEREDIRECT",new BooleanDataType());
			UseRedirect.ExtendedGroupName       =   extgrp;
			UseRedirect.Order                   =   80;
			UseRedirect.Value                   =   StStr.strTrue;
            UseRedirect.EnglishName             =   "Use Page Url redirect";
            UseRedirect.Description             =   "When selected the selected pages url will be sent as init parameters to silverlight module.";
            bSettings.AddSetting(UseRedirect);


            for ( int i=0 ; i < 20 ; i++ )
            {
                string defWelcome               =   StStr.PageDefaultWelcome.ToString();

				SettingItemSpecial PageUrl      =   new SettingItemSpecial(string.Format("SILVER_PAGE{0}",i),new PageTreeDataType());
				PageUrl.Value                   =   defWelcome; //default Welcome
				PageUrl.Order                   =   90+i*10;
                PageUrl.ExtendedGroupName       =   extgrp;
				PageUrl.EnglishName             =   string.Format("Page url {0}",i);
				PageUrl.Description             =   "Select a page to use it as a redirect url for silverlight module.";
				bSettings.AddSetting(PageUrl);
            }
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModuleSI InitSettings END.",ModuleTraceSwitch.Sw.Info);
        }
        /// <summary>
        /// Used to set the display value in ModuleOwner when loaded from DB
        /// </summary>
        void ModuleOwner_SettingItemsEvent(object sender, SettingItemsEventArgs e)
        {
            if ( e.EventType != SettingItemsEventType.Loaded )
                return;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SilverModuleSI ModuleOwner_SettingItemsEvent Guid: {0}", e.Data),ModuleTraceSwitch.Sw.Info);
            Guid custId                 =   new Guid((string)e.Data);
            if ( custId == Guid.Empty )
                return;
            ADNDynSystemUser dynac      =    DynEntity.GetFromCache<ADNDynSystemUser>(CrmStr.systemuser,Wrapper,new ResetWrapperHandler(ResetWrapper),custId);
            WSListDataType defAcc       =   (WSListDataType )((SettingItem)sender).DataType;
            defAcc.DisplayTextValue     =   dynac.fullname;
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SilverModuleSI ModuleOwner_SettingItemsEvent END name: {0}", dynac.name),ModuleTraceSwitch.Sw.Info);
        }
    }

    public partial class SilverModule : PortalCRMModuleControl
	{
        /// <summary>
        /// No entity needed here
        /// </summary>
        public override bool NeedAttachedEntity
        {
            get
            {
                return false;
            }
        }

		public override Guid GuidID 
		{
			get
			{
				return new Guid("{0FA24F04-FB1A-4638-BB87-2BA48FFCF2C7}");
			}
		}

		/// <summary>
		/// Ctor
		/// </summary>
		public SilverModule() 
		{
            if ( ModuleTraceSwitch.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModule Ctor Called.",ModuleTraceSwitch.Sw.Info);
        }

        public override string ExtendedResourcesGroup 
		{
            get
            {
       			const string extgrp                 =   "SILVERMODULE";
                return extgrp;
            }
		}

        public override void InitPortalModuleControl(ModuleSettingsDictionary bSettings)
        {
            PortalModuleInitializer =   new SilverModuleSI(bSettings,this);
        }

        protected void Page_Load(object sender, System.EventArgs e)
		{
            if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SilverModule Page_Load BEG CRM IsPostBack: {0}, IsInAsyncPostBack: {1}",IsPostBack,IsInAsyncPostBack),SilverTrace.Sw.Info);
            if ( !IsPostBack )
            {
                string silverSrc        =   Settings["SILVER_SRC"].FullPath;
                Unit wdt                =   Settings["SILVER_WIDTH"].ToUnit();
                Unit hgt                =   Settings["SILVER_HEIGHT"].ToUnit();
                Color bkCol             =   Settings["SILVER_BACKCOLOR"].ToColor();
                bool enableHtmlAccess   =   Settings["SILVER_ENABLEHTMLACCESS"].ToBool();
                string initParams       =   Settings["SILVER_INITPARAMS"].Value.Trim();
                StringBuilder sb1       =   new StringBuilder();
                sb1.AppendFormat("PtId={0},PgId={1},MdId={2},CRM={3}",
                    new object[]{PortalID,PageID,ModuleID,IsUnderCRM});
                if ( !string.IsNullOrEmpty(initParams) )
                    sb1.AppendFormat(",{0}",initParams);
                bool usePageRedirect    =   Settings["SILVER_USEPAGEREDIRECT"].ToBool();
                if ( usePageRedirect )
                {
                    for ( int i=0 ; i < 20 ; i++ )
                    {
                        int pageid  =   Settings[string.Format("SILVER_PAGE{0}",i)].ToInt();
                        string url  =   HttpUrlBuilder.BuildUrl(pageid);
                        sb1.AppendFormat(",P{0}={1}",i,url);
                    }
                }
                initParams              =   sb1.ToString();


                StringBuilder sb        =   new StringBuilder();
                sb.AppendFormat("<object  data=\"data:application/x-silverlight-2,\" type=\"application/x-silverlight-2\" width='{0}' height='{1}'>",wdt,hgt);
                sb.AppendFormat("<param name='source' value='{0}'/>",silverSrc);
                sb.Append("<param name='onError' value='onSilverlightError' />");
                sb.Append("<param name='Windowless' value='true' />");
                sb.AppendFormat("<param name='background' value='{0}' />",ColorTranslator.ToHtml(bkCol));
                sb.Append("<param name='minRuntimeVersion' value='3.0.40624.0' />");
                sb.Append("<param name='autoUpgrade' value='true' />");
                sb.AppendFormat("<param name='initParams' value='{0}' />",initParams);
                sb.AppendFormat("<param name='enableHtmlAccess' value='{0}' />",enableHtmlAccess);
                sb.Append(
                    "<a href=\"http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0\" style='text-decoration:none'>" +
                    "<img src=\"http://go.microsoft.com/fwlink/?LinkId=108181\" alt=\"Get Microsoft Silverlight\" style='border-style:none'/></a></object>");
                Literal lit             =   new Literal();
                lit.Text                =   sb.ToString();
                silverplaceholder.Controls.Add(lit);
            }
            if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModule Page_Load END.",SilverTrace.Sw.Info);
		}

        void AjaxManager_AjaxRequest(object sender,AjaxRequestEventArgs e)
        {
			if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SilverModule AjaxManager_AjaxRequest argument: '{0}'",e.Argument),SilverTrace.Sw.Info);
            string arg                      =   e.Argument;
            string[] args                   =   arg.Split(new char[]{','});
		    if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SilverModule AjaxManager_AjaxRequest args.Length: '{0}'",args.Length),SilverTrace.Sw.Info);
            if ( args.Length < 15 )
            {
                return;
            }
            string action                   =   args[0];
            
            string companyname              =   args[1];
            string activity                 =   args[2];    
            string lastname                 =   args[3];
            string jobtitle                 =   args[4];
            string telephone1               =   args[5];
            string emailaddress1            =   args[6];
            string street                   =   args[7];
            string city                     =   args[8];
            string zip                      =   args[9];
            string country                  =   args[10];
            string employees                =   args[11];
            string salesRep                 =   args[12];
            string Users                    =   args[13];
            string ServiceLevel             =   args[14];


            ADNDynLead newLead              =   new ADNDynLead(Wrapper,string.Empty,lastname);
            newLead.companyname             =   companyname;
            string fmt                      =   LocalizeHelper.Localize("SILVER_LEAD_SUBJECT","{0} for {1} by {2} on: {3} at {4:g}");
            newLead.subject                 =   string.Format(fmt,new object[]{action,companyname,lastname,portalSettings.PortalAlias,DateTime.Now});
            fmt                             =   LocalizeHelper.Localize("SILVER_LEAD_DESCRIPTION","Activity: {0}, Employees: {1}, Sales representatives: {2}, requested users: {3}, Service Level: {4}");
            newLead.description             =   string.Format(fmt,new object[]{activity,employees,salesRep,Users,ServiceLevel});
            newLead.jobtitle                =   jobtitle;
            newLead.telephone1              =   telephone1;
            newLead.emailaddress1           =   emailaddress1;
            newLead.address1_line1          =   street;
            newLead.address1_city           =   city;
            newLead.address1_postalcode     =   zip;
            newLead.address1_country        =   country;
            Guid ownerid                    =   Settings["SILVER_OWNER"].ToGuid();
            newLead.ownerid                 =   ownerid;

            newLead.numberofemployees       =   int.Parse(employees);


            Guid lId                        =   newLead.adminCreate();

            fmt                             =   LocalizeHelper.Localize("SILVER_NEW_LEAD","New lead created from site {0}, please call it");
            string subject                  =   string.Format(fmt,portalSettings.PortalAlias);
            ADNDynActivityTask task         =   new ADNDynActivityTask(Wrapper,subject);
            task.description                =   newLead.description;
            task.ownerid                    =   ownerid;
            task.category                   =   portalSettings.PortalAlias;
            task.prioritycode               =   2; // high
            task.DefaultRegardingObjectName =   CrmStr.lead;
            task.regardingobjectid          =   lId;
            Guid taslId                     =   task.adminCreate();
            if (SilverTrace.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SilverModule AjaxManager_AjaxRequest END task created lead: {0}, leadId: {1}, task: {2}", lastname,lId,taslId), SilverTrace.Sw.Info);
        }

        protected override void OnPreRender(EventArgs e)
        {
            if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]SilverModule OnPreRender BEG CRM IsPostBack: {0}, IsInAsyncPostBack: {1}",IsPostBack,IsInAsyncPostBack),SilverTrace.Sw.Info);
            if ( !IsInAsyncPostBack )
            {
                string gPath    =   Path.ToAbsolute(Config.PortalScriptsPath + "/ADNSilverlight.js");
                ((ADNPage)Page).RegisterADNClientScriptInclude("SilverScript", gPath);
            }
            base.OnPreRender(e);
            if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]CrmLocalizerManager OnPreRender END.",SilverTrace.Sw.Info);
            
            base.OnPreRender(e);
        }

		#region Std Overrides
		override protected void OnInit(EventArgs e)
		{
            if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModule OnInit BEG.",SilverTrace.Sw.Info);
			InitializeComponent();
			base.OnInit(e);
            if ( SilverTrace.Sw.TraceVerbose )
                Trace2.WriteLine( "[V]SilverModule OnInit END.",SilverTrace.Sw.Info);
		}
		
		private void InitializeComponent()
		{
            Load    +=  new EventHandler(Page_Load);
            RadAjaxManager aj                               =   (RadAjaxManager)Page.FindControl("RadAjaxManager1");
            if ( aj != null )
            {
                if ( SilverTrace.Sw.TraceVerbose )
                    Trace2.WriteLine("[V]SilverModule InitializeComponent AjaxRequest Ok.",SilverTrace.Sw.Info);
                aj.AjaxRequest += new RadAjaxControl.AjaxRequestDelegate(AjaxManager_AjaxRequest);
            }
		}

        #endregion
	}
}
